<template>
  <!-- 粒子库 -->
  <vue-particles
      id="tsparticles"
      :particlesInit="particlesInit"
      :options="options"
  />
  <div class="formContainer">
    <h3>智慧学习平台</h3>
    <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="90px"
        size="large"
        class="ruleForm"
    >
      <el-form-item
          label="用户名"
          prop="username"
          style="width: 90%;"
      >
        <el-input
            v-model="ruleForm.username"
            autocomplete="off"
        />
      </el-form-item>
      <el-form-item
          label="密码"
          prop="password"
          style="width: 90%;"
      >
        <el-input
            v-model="ruleForm.password"
            type="password"
            autocomplete="off"
        />
      </el-form-item>
      <el-form-item>
        <el-button
            type="success"
            @click="submitForm(ruleFormRef)"
            style="width: 88%; background: #61c354;"
        >登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import {useUserStore} from '../store/useUserStore'
import {useRouter} from 'vue-router'
import {ref, reactive} from 'vue'
import {loadFull} from "tsparticles";
import axios from 'axios'
import {ElMessage} from 'element-plus'
import {options} from '../util/config.js'

// 粒子库方法
const particlesInit = async engine => {
  await loadFull(engine);
};
//ref获取表单对象
const ruleFormRef = ref()
const ruleForm = reactive({
  username: "",
  password: ""
})
const rules = reactive({
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
  ],
})
const {changeUser} = useUserStore()
const router = useRouter()
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const res = await axios.post(`/adminapi/users/login`, ruleForm)
      let {code, data} = res.data
      if (code === 0) {
        changeUser(data)
        router.push("/")
      } else {
        ElMessage.error('用户名密码不匹配')
      }
    } else {
      console.log('error submit!', fields)
    }
  })

}

</script>


<style lang="scss" scoped>
.formContainer {
  height: 300px;
  width: 500px;
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background: rgba(232, 104, 92, 0.5);
  padding: 20px;

  .ruleForm {
    margin-top: 50px;
  }

  h3 {
    font-size: 30px;
    text-align: center;
    margin-top: 20px;
  }

  :deep(.el-form-item__label) {
    color: white;
    font-size: 16px;
    font-weight: 700;
  }

}
</style>